package com.qiyang.login.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Repository;

import java.util.Date;
import java.util.concurrent.TimeUnit;

/**
 * Created on 2018/5/9.
 *
 * @author sehuaqi.
 * 描述：操作Redis接口
 */
@Repository
public class RedisDao {

    Logger logger = LoggerFactory.getLogger(RedisDao.class);

    @Autowired
    private StringRedisTemplate template;

    /**
     * 设置缓存值，默认有效时间为1分钟
     *
     * @param key
     * @param val
     */
    public void setKey(String key, String val) {
        logger.info("< 设置缓存值：{}===>{}(1分钟有效)>", key, val);
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key, val, 1, TimeUnit.MINUTES);
    }

    /**
     * @param key
     * @param val
     * @param timeout 单位默认为秒
     */
    public void setKey(String key, String val, Long timeout) {
        logger.info("< 设置缓存值：{}===>{}({}秒有效)>", key, val, timeout);
        ValueOperations<String, String> ops = template.opsForValue();
        logger.info("<当前时间：{}>",new Date());
        ops.set(key, val, timeout, TimeUnit.SECONDS);
    }

    /**
     * @param key
     * @param val
     * @param timeout
     * @param unit
     */
    public void setKey(String key, String val, Long timeout, TimeUnit unit) {
        logger.info("< 设置缓存值：{}===>{}({} {} 有效)>", key, val, timeout, unit.toString());
        logger.info("<当前时间：{}>",new Date());
        ValueOperations<String, String> ops = template.opsForValue();
        ops.set(key, val, timeout, unit);
    }

    public String getValue(String key) {
        ValueOperations<String, String> ops = this.template.opsForValue();
        String val = ops.get(key);
        logger.info("< 获取缓存值：{}===>{} >", key, val);
        return val;
    }

}
